@file:OptIn(ExperimentalMaterial3Api::class)

package com.ljj.bitetime.ui.activity

import android.content.Context
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.activity.compose.setContent
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricPrompt
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import com.google.gson.Gson
import com.ljj.bitetime.data.local.database.AppDatabase
import com.ljj.bitetime.data.local.entity.OrderEntity
import com.ljj.bitetime.item.Cart
import com.ljj.bitetime.item.Dish
import com.ljj.bitetime.item.Order
import com.ljj.bitetime.item.OrderItem
import com.ljj.bitetime.ui.theme.BiteTimeTheme
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.Locale
import java.util.UUID

class CheckoutActivity : FragmentActivity() {
    private val context = this

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val cart = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            intent.getParcelableExtra("cart", Cart::class.java)
        } else {
            @Suppress("DEPRECATION")
            intent.getParcelableExtra("cart") as Cart?
        } ?: Cart()
        setContent {
            BiteTimeTheme {
                CheckoutScreen(cart = cart, onNavigateBack = { finish() })
            }
        }
    }

    fun showBiometricPrompt(
        activity: FragmentActivity,
        onSuccess: () -> Unit,
        onError: () -> Unit
    ) {
        val biometricManager = BiometricManager.from(activity)
        when (biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK)) {
            BiometricManager.BIOMETRIC_SUCCESS -> {
                val executor = ContextCompat.getMainExecutor(activity)
                val biometricPrompt = BiometricPrompt(
                    activity, executor,
                    object : BiometricPrompt.AuthenticationCallback() {
                        override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) { onSuccess() }
                        override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { onError() }
                        override fun onAuthenticationFailed() { onError() }
                    })
                val promptInfo = BiometricPrompt.PromptInfo.Builder()
                    .setTitle("生物识别验证")
                    .setSubtitle("请验证指纹以完成支付")
                    .setNegativeButtonText("取消")
                    .build()
                biometricPrompt.authenticate(promptInfo)
            }
            else -> onSuccess()
        }
    }

    suspend fun saveOrderToDatabase(context: Context, order: Order): Boolean {
        val database = AppDatabase.getDatabase(context)
        val itemsJson = Gson().toJson(order.items)
        val orderEntity = OrderEntity(
            id = order.id,
            itemsJson = itemsJson,
            totalPrice = order.totalPrice
        )
        val result = database.orderDao().insertOrder(orderEntity)
        return result != -1L
    }

    @Composable
    fun CheckoutScreen(cart: Cart, onNavigateBack: () -> Unit) {
        var orderPlaced by remember { mutableStateOf(false) }
        var isLoading by remember { mutableStateOf(false) }
        val scope = rememberCoroutineScope()
        if (orderPlaced) {
            OrderSuccessScreen(onNavigateBack = onNavigateBack)
        } else {
            Scaffold(
                topBar = {
                    TopAppBar(
                        title = { Text("确认订单") },
                        navigationIcon = {
                            IconButton(onClick = onNavigateBack) {
                                Icon(
                                    imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                                    contentDescription = "返回"
                                )
                            }
                        }
                    )
                }
            ) { innerPadding ->
                Column(
                    modifier = Modifier
                        .padding(innerPadding)
                        .fillMaxSize()
                        .padding(16.dp)
                ) {
                    // 订单详情
                    Card(
                        modifier = Modifier
                            .fillMaxWidth()
                            .weight(1f),
                        shape = RoundedCornerShape(12.dp),
                        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
                    ) {
                        LazyColumn(
                            modifier = Modifier
                                .fillMaxSize()
                                .padding(16.dp)
                        ) {
                            item {
                                Text(
                                    text = "订单详情",
                                    style = MaterialTheme.typography.titleLarge,
                                    fontWeight = FontWeight.Bold,
                                    modifier = Modifier.padding(bottom = 16.dp)
                                )
                            }
                            items(cart.items.toList()) { (dish, quantity) ->
                                CheckoutItem(
                                    dish = dish,
                                    quantity = quantity
                                )
                            }
                            item {
                                HorizontalDivider(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(vertical = 16.dp)
                                )
                            }
                            item {
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(vertical = 8.dp),
                                    horizontalArrangement = Arrangement.SpaceBetween
                                ) {
                                    Text(
                                        text = "总价",
                                        style = MaterialTheme.typography.titleMedium,
                                        fontWeight = FontWeight.Bold
                                    )
                                    Text(
                                        text = "￥${String.format(Locale.CHINA, "%.2f", cart.totalPrice)}",
                                        style = MaterialTheme.typography.titleMedium,
                                        fontWeight = FontWeight.Bold,
                                        color = MaterialTheme.colorScheme.primary
                                    )
                                }
                            }
                        }
                    }
                    // 结账按钮
                    Button(
                        onClick = {
                            showBiometricPrompt(
                                activity = context,
                                onSuccess = {
                                    isLoading = true
                                    scope.launch {
                                        val randomDelay = (500..2000).random().toLong()
                                        delay(randomDelay)
                                        val orderItems = cart.items.map { (dish, quantity) ->
                                            OrderItem(dish, quantity)
                                        }
                                        val order = Order(
                                            id = UUID.randomUUID().toString(),
                                            items = orderItems,
                                            totalPrice = cart.totalPrice
                                        )
                                        if (saveOrderToDatabase(context, order)) {
                                            orderPlaced = true
                                            context.setResult(RESULT_OK)
                                        } else {
                                            Toast.makeText(
                                                context,
                                                "订单保存失败",
                                                Toast.LENGTH_SHORT
                                            ).show()
                                        }
                                        isLoading = false
                                    }
                                },
                                onError = {
                                    isLoading = false
                                }
                            )
                        },
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(top = 16.dp)
                            .height(50.dp),
                        enabled = cart.totalPrice > 0 && !isLoading,
                        shape = RoundedCornerShape(8.dp)
                    ) {
                        if (isLoading) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(24.dp),
                                color = MaterialTheme.colorScheme.onPrimary
                            )
                        } else {
                            Text(
                                text = "确认支付 ￥${String.format(Locale.CHINA, "%.2f", cart.totalPrice)}",
                                fontSize = 16.sp,
                                fontWeight = FontWeight.Bold
                            )
                        }
                    }
                }
            }
        }
    }

    @Composable
    fun CheckoutItem(dish: Dish, quantity: Int) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 8.dp),
            verticalAlignment = Alignment.Top
        ) {
            Column(
                modifier = Modifier.weight(1f)
            ) {
                Text(
                    text = dish.name,
                    style = MaterialTheme.typography.bodyLarge,
                    fontWeight = FontWeight.Bold
                )
                if (!dish.options.isEmpty()) {
                    Text(
                        text = dish.options.joinToString("，"),
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.padding(top = 4.dp)
                    )
                }
                Text(
                    text = "￥${dish.basePrice}",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.secondary,
                    modifier = Modifier.padding(top = 4.dp)
                )
            }
            Text(
                text = "x$quantity",
                style = MaterialTheme.typography.bodyMedium,
                modifier = Modifier.padding(start = 8.dp)
            )
        }
    }

    @Composable
    fun OrderSuccessScreen(onNavigateBack: () -> Unit) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(MaterialTheme.colorScheme.background),
            contentAlignment = Alignment.Center
        ) {
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                modifier = Modifier.padding(32.dp)
            ) {
                Icon(
                    imageVector = Icons.Default.Check,
                    contentDescription = "订单成功",
                    tint = MaterialTheme.colorScheme.primary,
                    modifier = Modifier
                        .size(80.dp)
                        .padding(bottom = 16.dp)
                )
                Text(
                    text = "订单提交成功",
                    style = MaterialTheme.typography.headlineSmall,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.padding(bottom = 8.dp)
                )
                Text(
                    text = "感谢您的购买，餐品正在准备中",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.padding(bottom = 32.dp)
                )
                Button(
                    onClick = onNavigateBack,
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(50.dp)
                ) {
                    Text(
                        text = "返回首页",
                        fontSize = 16.sp
                    )
                }
            }
        }
    }
}